//
//  AppDelegate_iPad.m
//  Tazama NGO
//
//  Created by jsheriff on 3/2/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "AppDelegate_iPad.h"
#import "FieldObservationDB.h"
#import "MTLocationManager.h"
#import "MTStartupUtilities.h"
#import "KmlElementDB.h"
#import "MapViewController_iPad.h"
#import "Settings.h"

@implementation AppDelegate_iPad

@synthesize window, areSettingsValid;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [MTStartupUtilities registerDefaultsFromSettingsBundle];
    if (![self areSettingsValid]) {
        
        NSLog(@"Required user defaults not found");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Required Settings" message:@"Please enter the host name, port, user ID, and full user name in settings." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];   
    }
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"TazamaData.db"];
    
    [MTStartupUtilities copyFileFromBundleToDocumentsDirectory:@"TazamaData.db"];
    
    [[FieldObservationDB sharedInstance] initFromPath:dbPath];
    MapViewController_iPad *mapViewController = [[MapViewController_iPad alloc] initWithNibName:@"MapViewController_iPad" bundle:nil];
    [self.window addSubview:mapViewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

-(BOOL)areSettingsValid{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *postHost = [defaults objectForKey:kHostName];
    if (postHost.length == 0) return NO;
    
    NSString *feedURLStr = [defaults objectForKey:feedURL];
    if (feedURLStr.length == 0) return NO;
    
    NSString *email = [defaults objectForKey:kUserId];
    if (email.length == 0) return NO;
    
    NSString *kmlUpdateTime = [defaults objectForKey:kKmlFeedUpdatePeriod];
    if (kmlUpdateTime.length == 0 || [kmlUpdateTime intValue] < 10 || [kmlUpdateTime intValue] > 120) return NO;
    
    NSString *currCotTypeStr = [defaults objectForKey:currCoTType];
    if (currCotTypeStr.length == 0 || [currCotTypeStr isEqualToString:@"None"]) return NO;
    
    NSString *uidStr = [defaults objectForKey:uniqueID];
    if (uidStr.length == 0) return NO;
    
    NSString *sitrepKeywordStr = [defaults objectForKey:sitrepKeyword];
    if (sitrepKeywordStr.length == 0) return NO;
    
    NSString *posKeywordStr = [defaults objectForKey:posKeyword];
    if (posKeywordStr.length == 0) return NO;
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    /*
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] startPollingFeed];
    [[MTLocationManager sharedInstance] applicationOpened:sendReport];*/
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] stopPollingFeed];
    [[MTLocationManager sharedInstance] applicationClosed:sendReport];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive.
     */
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] startPollingFeed];
    [[MTLocationManager sharedInstance] applicationOpened:sendReport];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
    [window release];
    [super dealloc];
}


@end
